package com.flaskpy.web.eternity.auth.jwt.config.filter;

import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * jwt 错误过滤器
 */
public class JwtExceptionFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }
        catch (ExpiredJwtException e){
            sendError(httpServletResponse,new HashMap<String,String>(){{ put("error","jwt令牌超时"); }});
        }
        catch (MalformedJwtException e){
            sendError(httpServletResponse,new HashMap<String,String>(){{ put("error","jwt令牌错误"); }});
        }
        catch (SignatureException e){
            sendError(httpServletResponse,new HashMap<String,String>(){{ put("error","jwt令牌签名错误"); }});
        }
        catch (UnsupportedJwtException e){
            sendError(httpServletResponse,new HashMap<String,String>(){{ put("error","jwt令牌未知错误"); }});
        }
        catch (Exception e){
            e.printStackTrace();
            sendError(httpServletResponse,new HashMap<String,String>(){{ put("error","jwt过滤器外出错程序出错"); }});
        }
    }

    protected void sendError(HttpServletResponse response,Object r) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();

            out.append(JSONUtil.toJsonStr(r));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
